package org.tamal.struts.struts;

import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

/**
 * Locale Action generates Countries and languages.
 * @author Tamal Kanti Nath
 */
@Results({
    @Result(name = Action.SUCCESS, type = "json", params = {
        "excludeNullProperties", "true", "noCache", "true" }) })
@ParentPackage("json-default")
public final class LocaleAction extends ActionSupport {

    private static final long serialVersionUID = -1507407605858768014L;

    private String country;
    private String language;
    private Map<String, String> countries;
    private Map<String, String> languages;

    /**
     * Returns the languages.
     * @return the languages
     */
    public Map<String, String> getLanguages() {
        return languages;
    }

    /**
     * Sets the language.
     * @param language the languages to set
     */
    public void setLanguage(String language) {
        this.language = language;
    }

    /**
     * Returns the countries.
     * @return the countries
     */
    public Map<String, String> getCountries() {
        return countries;
    }

    /**
     * Sets the country.
     * @param country the country to set
     */
    public void setCountry(String country) {
        this.country = country;
    }

    @Override
    public String execute() {
        if (country == null && language == null) {
            countries = new TreeMap<>();
            languages = new TreeMap<>();
            for (Locale l : Locale.getAvailableLocales()) {
                countries.put(l.getCountry(), l.getDisplayCountry());
                languages.put(l.getLanguage(), l.getDisplayLanguage());
            }
        }
        if (country != null && language == null) {
            languages = new TreeMap<>();
            for (Locale l : Locale.getAvailableLocales()) {
                if (country.equalsIgnoreCase(l.getCountry())
                        || country.equalsIgnoreCase(l.getDisplayCountry())) {
                    languages.put(l.getLanguage(), l.getDisplayLanguage());
                }
            }
        }
        if (country == null && language != null) {
            countries = new TreeMap<>();
            for (Locale l : Locale.getAvailableLocales()) {
                if (language.equalsIgnoreCase(l.getLanguage())
                        || language.equalsIgnoreCase(l.getDisplayLanguage())) {
                    countries.put(l.getCountry(), l.getDisplayCountry());
                }
            }
        }
        return SUCCESS;
    }
}
